<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="RTOS TencentOS-tiny">
    <meta name="description" content="嵌入式 STM32 物联网领域的教程及精彩内容分享">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>02-优先级抢占调度到底是怎么回事 | Mculover666</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Mculover666</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-list" style="zoom: 0.6;"></i>
      
      <span>系列教程</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/posts/578764034/">
          
          <span>STM32CubeMX</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>CSDN</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/download" class="waves-effect waves-light">
      
      <i class="fas fa-download" style="zoom: 0.6;"></i>
      
      <span>资源下载</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Mculover666</div>
        <div class="logo-desc">
            
            嵌入式 STM32 物联网领域的教程及精彩内容分享
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-list"></i>
			
			系列教程
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/posts/578764034/ " style="margin-left:75px">
				  
		          <span>STM32CubeMX</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			CSDN
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/download" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-download"></i>
			
			资源下载
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/20.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">02-优先级抢占调度到底是怎么回事</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                                <span class="chip bg-color">RTOS内功修炼记</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/RTOS/" class="post-category">
                                RTOS
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-08-01
                </div>
                

                

                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>内容导读：</p>
<p>本文从任务如何切换开始讲起，引出RTOS内核中的就绪列表、优先级表，一层一层为你揭开RTOS内核优先级抢占式调度方法的神秘面纱，只有对内核的深入了解，才能创造出更好的应用。</p>
<hr>

<h1 id="1-知识点回顾"><a href="#1-知识点回顾" class="headerlink" title="1.知识点回顾"></a>1.知识点回顾</h1><h2 id="1-1-上文回顾"><a href="#1-1-上文回顾" class="headerlink" title="1.1. 上文回顾"></a>1.1. 上文回顾</h2><p>上篇文章讲述了任务的三大元素：任务控制块、任务栈、任务入口函数，并讲述了编写RTOS任务入口函数时三个重要的注意点。</p>
<p>如果你还没有阅读上一篇文章，请先阅读，这有助于对本文的理解：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://mculover666.blog.csdn.net/article/details/106337971">RTOS内功修炼记（一）—— 任务到底应该怎么写？</a></li>
</ul>
<h2 id="1-2-双向循环链表"><a href="#1-2-双向循环链表" class="headerlink" title="1.2. 双向循环链表"></a>1.2. 双向循环链表</h2><p>双向链表是链表的一种，区别在于每个节点除了后继指针外，还有一个前驱指针，双向链表的节点长下面这样：<br><img src="https://img-blog.csdnimg.cn/20200602164813200.png#pic_center"></p>
<p>如果你对双向循环列表的实现及使用还不熟悉，请一定要先阅读这篇文章：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://mculover666.blog.csdn.net/article/details/106499831">TencentOS-tiny中的双向循环链表的实现及使用</a></li>
</ul>
<h1 id="2-任务是如何切换的"><a href="#2-任务是如何切换的" class="headerlink" title="2. 任务是如何切换的"></a>2. 任务是如何切换的</h1><p>在RTOS内核中，一个任务切换到下一个任务的原理是：<strong>手动触发PendSV异常，在PendSV异常服务函数中实现任务切换</strong>。</p>
<h2 id="2-1-如何触发PendSV异常"><a href="#2-1-如何触发PendSV异常" class="headerlink" title="2.1. 如何触发PendSV异常"></a>2.1. 如何触发PendSV异常</h2><p>stm32中，将中断及状态控制寄存器 <code>Interrupt control and state register (ICSR)</code> 的第28位置1，即可手动触发 PendSV 异常，如图：<br><img src="https://img-blog.csdnimg.cn/2020060308385311.png"></p>
<p>tos中触发异常的底层函数为<code>port_context_switch</code>，实现在 <code>arch\arm\arm-v7m\cortex-m4\armcc\port_s.S</code>中，如下：</p>
<pre><code class="asm">    GLOBAL port_context_switch
port_context_switch
    LDR     R0, =NVIC_INT_CTRL
    LDR     R1, =NVIC_PENDSVSET
    STR     R1, [R0]
    BX      LR
</code></pre>
<p>上面这段汇编猛一看有点难，再看看两个值具体是多少：</p>
<pre><code class="asm">NVIC_INT_CTRL   EQU     0xE000ED04
NVIC_PENDSVSET  EQU     0x10000000
</code></pre>
<p>所以上面这段汇编代码，不正是完成了将寄存器 ICSR（代码中是NVIC_INT_CTRL） 的第28位置1的操作吗？</p>
<h2 id="2-2-异常服务中实现任务切换"><a href="#2-2-异常服务中实现任务切换" class="headerlink" title="2.2. 异常服务中实现任务切换"></a>2.2. 异常服务中实现任务切换</h2><p>在 stm32 中 PendSV 的异常服务函数名为 PendSV_Handler，默认在stm32l4xx_it.c中提供了一个弱定义，所以tos中的实现直接重定义此函数即可，源码在 <code>arch\arm\arm-v7m\cortex-m4\armcc\port_s.S</code>中，主要步骤有四个：</p>
<p>① <strong>关闭全局中断</strong>（NMI 和 HardFault 除外），防止任务切换过程被中断：</p>
<pre><code class="c">CPSID   I
</code></pre>
<p>② <strong>保存上文环境</strong>：保存当前CPU寄存器组的值、PSP栈顶指针的值到任务栈中；</p>
<p>③ <strong>加载下文环境</strong>：加载当前任务栈中的值到CPU寄存器组、PSP栈顶指针中；</p>
<p>④ <strong>打开全局中断</strong>，实时响应系统所有中断：</p>
<pre><code class="c">CPSIE   I
</code></pre>
<p>记住任务切换的这四个过程即可，深入研究每行汇编指令是什么意思，没有太大的作用和帮助。</p>
<h2 id="2-3-CPU何时响应PendSV异常"><a href="#2-3-CPU何时响应PendSV异常" class="headerlink" title="2.3. CPU何时响应PendSV异常"></a>2.3. CPU何时响应PendSV异常</h2><p>我们都知道，<strong>高优先级的中断会打断低优先级的中断</strong>，这也是系统实时性的一个重要保障，所以就引入了一个问题：</p>
<p>相比起GPIO中断、定时器中断、串口中断这些外部中断，PendSV异常的优先级更高呢？还是更低呢？</p>
<p>想象这样一种情况：</p>
<p>① CPU正在开心的运行着任务1……</p>
<p>② 此时你按下了按键，产生了一个GPIO中断，CPU收到后马上跑去执行中断处理函数……</p>
<p>③ 处理过程中，此时系统产生了一个PendSV异常，CPU收到后，嘲讽了一句：“我就是从普通任务跑来处理中断的，还没处理完，现在又让我执行下一个普通任务，脑子抽风了？”，说完继续处理中断……</p>
<p>所以说，无论任务的优先级有多高，它都没有中断高，<strong>系统的PendSV异常优先级必须设为最低的</strong>，以避免在外部中断服务函数中产生任务切换。</p>
<p>设置PendSV异常优先级的寄存器如下，值可以为0-255：<br><img src="https://img-blog.csdnimg.cn/20200603085011203.png"></p>
<p>tos中在启动调度时设定pendsv异常的优先级，源码如下：</p>
<pre><code class="asm">NVIC_SYSPRI14   EQU     0xE000ED22
NVIC_PENDSV_PRI EQU     0xFF
</code></pre>
<p>同样，设置pendSV异常优先级为最低的汇编代码如下：</p>
<pre><code class="c">; set pendsv priority lowest
; otherwise trigger pendsv in port_irq_context_switch will cause a context switch in irq
; that would be a disaster
MOV32   R0, NVIC_SYSPRI14
MOV32   R1, NVIC_PENDSV_PRI
STRB    R1, [R0]
</code></pre>
<h1 id="3-就绪列表"><a href="#3-就绪列表" class="headerlink" title="3. 就绪列表"></a>3. 就绪列表</h1><h2 id="3-1-就绪列表长啥样"><a href="#3-1-就绪列表长啥样" class="headerlink" title="3.1. 就绪列表长啥样"></a>3.1. 就绪列表长啥样</h2><p>就绪列表其实就是好多条双向链表+一张优先级表，它的类型定义在<code>tos_sched.h</code>，如下：</p>
<pre><code class="c">typedef struct readyqueue_st
&#123;
    k_list_t    task_list_head[TOS_CFG_TASK_PRIO_MAX];
    uint32_t    prio_mask[K_PRIO_TBL_SIZE];
    k_prio_t    highest_prio;
&#125; readyqueue_t;
</code></pre>
<p>①<strong>给每个优先级都分配了一个双向链表的首节点，用于挂载该优先级的任务</strong>。</p>
<p>TOS_CFG_TASK_PRIO_MAX 是最大任务优先级，在tos_config.h中配置，默认是10：</p>
<pre><code class="c">#define TOS_CFG_TASK_PRIO_MAX           10u
</code></pre>
<p>节点类型 k_list_t 是一个双向链表节点类型：</p>
<pre><code class="c">typedef struct k_list_node_st
&#123;
    struct k_list_node_st *next;
    struct k_list_node_st *prev;
&#125; k_list_t;
</code></pre>
<p>所有双向链表节点初始化完毕之后，每一个双向结点的next指针指向自己（橙色线），prev指针也指向自己，如图：<br><img src="https://img-blog.csdnimg.cn/20200601211302945.png"></p>
<p>② <strong>用于指示系统目前所使用优先级的优先级表</strong>。</p>
<p>优先级表的大小由宏定义 K_PRIO_TBL_SIZE 决定：</p>
<pre><code class="c">#define K_PRIO_TBL_SIZE         ((TOS_CFG_TASK_PRIO_MAX + 31) / 32)
</code></pre>
<p>这儿定义的时候比较讲究，如果最大优先级不大于32，则该宏的值为1，使用一个uint32_t类型的变量即可，每个优先级的表示占一位。</p>
<p>初始化后的优先级表长下面这个样子：<br><img src="https://img-blog.csdnimg.cn/20200601214107206.png"><br>③ <strong>最高优先级指示成员</strong>。</p>
<p>就绪列表中的 highest_prio 成员是 k_prio_t 类型，其实就是一个uint8_t类型：</p>
<pre><code class="c">typedef uint8_t             k_prio_t;
</code></pre>
<p>该成员表示系统中当前所存在任务的最高优先级，默认是系统定义的最大优先级。</p>
<h2 id="3-2-系统中的就绪列表"><a href="#3-2-系统中的就绪列表" class="headerlink" title="3.2. 系统中的就绪列表"></a>3.2. 系统中的就绪列表</h2><p>系统中有多少条就绪列表呢？</p>
<p>对了，答案当然是：<strong>仅有唯一的一条就绪列表</strong>。</p>
<p>在<code>tos_global.h</code>中声明，便于在整个内核的所有文件中使用：</p>
<pre><code class="c">/* ready queue of tasks                         */
extern readyqueue_t         k_rdyq;
</code></pre>
<p>在<code>tos_global.c</code>中定义：</p>
<pre><code class="c">readyqueue_t        k_rdyq;
</code></pre>
<p><strong>记住它的名字，它叫k_rdyq</strong>，k就是kernel，rdyq就是ready queue的缩写，后面会经常出现。</p>
<h2 id="3-3-初始化就绪列表"><a href="#3-3-初始化就绪列表" class="headerlink" title="3.3. 初始化就绪列表"></a>3.3. 初始化就绪列表</h2><p>知道了就绪列表长啥样，就绪列表的初始化就变得非常简单了，都是常规操作，在<code>tos_sched.c</code>文件中实现：</p>
<pre><code class="c">__KNL__ void readyqueue_init(void)
&#123;
    uint8_t i;

    k_rdyq.highest_prio = TOS_CFG_TASK_PRIO_MAX;

    for (i = 0; i &lt; TOS_CFG_TASK_PRIO_MAX; ++i) &#123;
        tos_list_init(&amp;k_rdyq.task_list_head[i]);
    &#125;

    for (i = 0; i &lt; K_PRIO_TBL_SIZE; ++i) &#123;
        k_rdyq.prio_mask[i] = 0;
    &#125;
&#125;
</code></pre>
<p>第①步是设置最高优先级成员的初始值，为系统当前配置的最高优先级；</p>
<p>第②步是遍历初始化每个双向链表节点；</p>
<p>第③步就是初始化优先级表的所有值，为0。</p>
<h1 id="4-任务如何挂载到就绪列表"><a href="#4-任务如何挂载到就绪列表" class="headerlink" title="4. 任务如何挂载到就绪列表"></a>4. 任务如何挂载到就绪列表</h1><p>在任务创建API的最后，会调用 readyqueue_add_tail 函数将任务加入到就绪列表中，那么，任务究竟是被如何挂载上去的呢？</p>
<p>此函数的源码实现如下：</p>
<pre><code class="c">__KNL__ void readyqueue_add_tail(k_task_t *task)
&#123;
    k_prio_t task_prio;
    k_list_t *task_list;

    task_prio = task-&gt;prio;
    task_list = &amp;k_rdyq.task_list_head[task_prio];

    if (tos_list_empty(task_list)) &#123;
        readyqueue_prio_mark(task_prio);
    &#125;

    tos_list_add_tail(&amp;task-&gt;pend_list, task_list);
&#125;
</code></pre>
<p>① <strong>获取该任务的优先级在就绪列表中所对应的首节点</strong>。</p>
<p>② <strong>在优先级表中记录此优先级</strong>。</p>
<p>判断系统中该优先级是否第一次出现，如果是，则将优先级表中此优先级的标志位置1，表示系统中存在此优先级的任务，并重新赋值就绪列表中的最高优先级指示成员（注：优先级值越小，表示优先级越高）：</p>
<pre><code class="c">__STATIC_INLINE__ void readyqueue_prio_insert(k_prio_t prio)
&#123;
    k_rdyq.prio_mask[K_PRIO_NDX(prio)] |= K_PRIO_BIT(prio);
&#125;

__STATIC_INLINE__ void readyqueue_prio_mark(k_prio_t prio)
&#123;
    readyqueue_prio_insert(prio);

    if (prio &lt; k_rdyq.highest_prio) &#123;
        k_rdyq.highest_prio = prio;
    &#125;
&#125;
</code></pre>
<p>举个例子，当我们创建了一个优先级为2的任务后，则优先级表如下：<br><img src="https://img-blog.csdnimg.cn/20200603092828739.png"></p>
<p>③ <strong>将该任务的任务控制块的pendlist节点，挂载到第一步获取到的首节点所指示的链表尾部</strong>。</p>
<p>任务控制块中的pend_list成员也是一个双向链表节点：</p>
<pre><code class="c">/**
 * task control block
 */
struct k_task_st &#123;
    //……
    
    k_list_t    pend_list;    /**&lt; when we are ready, our pend_list is in readyqueue; when pend, in a certain pend object&#39;s list. */

    //……
&#125;;
</code></pre>
<p>使用双向链表将此pendlist节点添加到第①步获取到的链表尾部，添加之后如图：<br><img src="https://img-blog.csdnimg.cn/20200603091817289.png"></p>
<h1 id="5-优先级抢占式调度"><a href="#5-优先级抢占式调度" class="headerlink" title="5. 优先级抢占式调度"></a>5. 优先级抢占式调度</h1><h2 id="5-1-基本调度规则"><a href="#5-1-基本调度规则" class="headerlink" title="5.1. 基本调度规则"></a>5.1. 基本调度规则</h2><p>理解了上面的三节内容，再来看优先级抢占式调度，简直就是水到渠成。</p>
<p>同样，先放上优先级抢占式调度的源码，在<code>tos_syc.c</code>中：</p>
<pre><code class="c">__KNL__ void knl_sched(void)
&#123;
    TOS_CPU_CPSR_ALLOC();

    if (unlikely(!tos_knl_is_running())) &#123;
        return;
    &#125;

    if (knl_is_inirq()) &#123;
        return;
    &#125;

    if (knl_is_sched_locked()) &#123;
        return;
    &#125;

    TOS_CPU_INT_DISABLE();
    k_next_task = readyqueue_highest_ready_task_get();
    if (knl_is_self(k_next_task)) &#123;
        TOS_CPU_INT_ENABLE();
        return;
    &#125;

    cpu_context_switch();
    TOS_CPU_INT_ENABLE();
&#125;
</code></pre>
<p>在源码中可以看到，优先级抢占式调度其实就是两个步骤：</p>
<p>① 获取就绪列表中的最高优先级的任务控制块指针；</p>
<p>② 启动上下文切换；</p>
<p>总结一下，优先级抢占式调度的规则就是：<strong>每当符合调度条件时时，就切换到就绪列表中优先级最高的任务开始运行</strong>。</p>
<h2 id="5-2-如何获取最高优先级的任务"><a href="#5-2-如何获取最高优先级的任务" class="headerlink" title="5.2. 如何获取最高优先级的任务"></a>5.2. 如何获取最高优先级的任务</h2><p>别忘了就绪列表中有一个成员叫highest_prio，该成员指示出了系统当前存在的最高优先级，可以很方便的获取到挂载最高优先级的任务链表，函数源码如下：</p>
<pre><code class="c">__KNL__ k_task_t *readyqueue_highest_ready_task_get(void)
&#123;
    k_list_t *task_list;

    task_list = &amp;k_rdyq.task_list_head[k_rdyq.highest_prio];
    return TOS_LIST_FIRST_ENTRY(task_list, k_task_t, pend_list);
&#125;
</code></pre>
<p>但是需要注意，在就绪列表上挂载的是任务控制块中的pend_list节点，如图：<br><img src="https://img-blog.csdnimg.cn/20200603094038353.png"></p>
<p>已知任务控制块中pend_list节点地址，如何知道它所在任务控制块的基地址呢？</p>
<p>其实它是通过 TOS_LIST_FIRST_ENTRY 这个宏来获取的，具体的使用方法，请阅读我在文章开头提出的第二篇文章。</p>
<h1 id="6-优先级表有什么用？"><a href="#6-优先级表有什么用？" class="headerlink" title="6. 优先级表有什么用？"></a>6. 优先级表有什么用？</h1><p>优先级表的作用是：<strong>在将任务从就绪列表中移出时，用来获取当前就绪列表中的最高优先级</strong>。</p>
<p>优先级抢占式调度器可是六亲不认的，才不管任务当前状态是什么，反正就是永远寻找调度列表中最高优先级的任务。</p>
<p>所以当任务调用要主动挂起时，必须要从就绪列表中移出，源码如下：</p>
<pre><code class="c">__API__ k_err_t tos_task_suspend(k_task_t *task)
&#123;
    TOS_CPU_CPSR_ALLOC();

    //一堆参数判断，省略了

    TOS_CPU_INT_DISABLE();

    if (task_state_is_ready(task))
    &#123; 
        // kill the good kid
        readyqueue_remove(task);
    &#125;
    task_state_set_suspended(task);

    TOS_CPU_INT_ENABLE();
    knl_sched();

    return K_ERR_NONE;
&#125;
</code></pre>
<p>其中核心的就绪列表移出函数 readyqueue_remove 源码如下：</p>
<pre><code class="c">__KNL__ void readyqueue_remove(k_task_t *task)
&#123;
    k_prio_t task_prio;
    k_list_t *task_list;

    task_prio = task-&gt;prio;
    task_list = &amp;k_rdyq.task_list_head[task_prio];

    tos_list_del(&amp;task-&gt;pend_list);

    if (tos_list_empty(task_list)) &#123;
        readyqueue_prio_remove(task_prio);
    &#125;

    if (task_prio == k_rdyq.highest_prio) &#123;
        k_rdyq.highest_prio = readyqueue_prio_highest_get();
    &#125;
&#125;
</code></pre>
<p>① 获取任务当前优先级在就绪列表中的首节点；</p>
<p>② 将该任务控制块与该条双向链表断开（并没有删除任务）；</p>
<p>③ 如果断开后该链表变空，则表示就绪列表中不存在该优先级的任务，在优先级表中将该位清零；</p>
<p>④ <strong>重新获取就绪列表中的最高优先级</strong>。</p>
<p>这个时候优先级表的作用就体现出来了，之前讲到，优先级表中记录了当前就绪列表中所存在任务的优先级，所以可以通过遍历查找优先级表，来获取到最高优先级，最后赋值给就绪列表中的指示成员。</p>
<p>源码如下：</p>
<pre><code class="c">__STATIC__ k_prio_t readyqueue_prio_highest_get(void)
&#123;
    uint32_t *tbl;
    k_prio_t prio;

    prio    = 0;
    tbl     = &amp;k_rdyq.prio_mask[0];

    while (*tbl == 0) &#123;
        prio += K_PRIO_TBL_SLOT_SIZE;
        ++tbl;
    &#125;
    prio += tos_cpu_clz(*tbl);
    return prio;
&#125;
</code></pre>
<h1 id="7-总结"><a href="#7-总结" class="headerlink" title="7. 总结"></a>7. 总结</h1><p>讲述了这么多内容，非常有必要来总结出值得注意的点：</p>
<p>① <strong>RTOS内核中通过手动触发PendSV异常来启动一次切换，任务切换在PendSV异常服务函数中实现</strong>。</p>
<p>② <strong>RTOS内核中PendSV异常的优先级被设为最低，避免在外部中断处理函数中产生任务切换</strong>。</p>
<p>③ <strong>RTOS内核所谓的优先级抢占式调度规则就是永远从就绪队列中找出最高优先级的任务来运行</strong>。</p>
<p>当然，有了优先级抢占式调度规则，才勉强撑起来了一个RTOS内核的肉体，什么时候进行调度，才是一个RTOS内核的灵魂，接下来的文章与大家再会，我是Mculover666，一个喜欢玩板子的小码农。</p>
<p><font color="red"><strong>接收更多精彩文章及资源推送，欢迎订阅我的微信公众号：『mculover666』。</strong></font><br><img src="https://img-blog.csdnimg.cn/20200202092055136.png"></p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Mculover666</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.mculover666.cn/posts/3835893929/">http://www.mculover666.cn/posts/3835893929/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Mculover666</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                                    <span class="chip bg-color">RTOS内功修炼记</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/we-chat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    
    <div class="livere-card card" data-aos="fade-up">
    <!-- 来必力City版安装代码 -->
    <div id="lv-container" class="card-content" data-id="city" data-uid="MTAyMC80Njg0OS8yMzM1MA">
        <script type="text/javascript">
            (function (d, s) {
                let j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') {
                    return;
                }

                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript。</noscript>
    </div>
    <!-- City版安装代码已完成 -->
</div>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/199163223/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/15.jpg" class="responsive-img" alt="03-内核到底是如何管理中断的">
                        
                        <span class="card-title">03-内核到底是如何管理中断的</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            RTOS内功修炼记
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-08-01
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RTOS/" class="post-category">
                                    RTOS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                        <span class="chip bg-color">RTOS内功修炼记</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/2730530468/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/7.jpg" class="responsive-img" alt="01-任务到底应该怎么写">
                        
                        <span class="card-title">01-任务到底应该怎么写</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            RTOS内功修炼记
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-08-01
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RTOS/" class="post-category">
                                    RTOS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                        <span class="chip bg-color">RTOS内功修炼记</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2016-2021</span>
            
            <span id="year">2016</span>
            <a href="/about" target="_blank">Mculover666</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">118.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2016";
                    var startMonth = "8";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="https://beian.miit.gov.cn" target="_blank">陇ICP备19002222号</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Mculover666" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:mculover666@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2412828003" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2412828003" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/wang-shi-wei-67-38/activities" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/wang-shi-wei-67-38/activities" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?6e1efa0988723a1db6356535db2ae6bd";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
